package com.quectel.cms.controller.village;


import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.log.annotation.Log;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-10-18 14:41:21
 */
@RestController
@RequestMapping("village")
@Tag(name = "VillageController", description = "小区相关api")
public class VillageController extends BaseController {

    @DubboReference
    private VillageService villageService;
    @DubboReference
    private VillageBuildingService villageBuildingService;

    /**
     * 根据参数查询小区列表
     */
    @GetMapping("queryAll")
    @Operation(summary = "根据参数查询小区列表")
    public Response<List<VillageDto>> queryAll() {

        Map<String, Object> params = Request.parseParams(httpServletRequest);
        super.fillAuthorityData(params);

        List<VillageDto> list = villageService.queryList(params);

        return Response.<List<VillageDto>>ok().wrap(list);
    }

    /**
     * 根据参数导出小区列表为excel文件
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "village:export")
    @Log(express = "导出小区列表")
    @Operation(summary = "根据参数导出小区列表为excel文件")
    public void exportExcel(@RequestParam Map<String, Object> params,
                            HttpServletResponse resp) {
        //查询列表数据
        Request request = Request.configParamsNotPage(params);

        super.fillAuthorityData(params);
        List<VillageDto> list = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 10000);
        while (true) {
            params.put("offset", pageNo++ * 10000);
            List<VillageDto> houseHoldDtos = villageService.queryList(params);
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(houseHoldDtos)) {
                break;
            }
            list.addAll(houseHoldDtos);

        }
        String[] headers = new String[]{"省份名称", "市名称", "区名称", "街道名称", "小区编码", "小区名称", "详细地址", "经度", "纬度"};
        List<String[]> dataList = new ArrayList<>();
        for (VillageDto data : list) {
            String[] item = new String[headers.length];
            item[0] = data.getProvinceName();
            item[1] = data.getCityName();
            item[2] = data.getDistrictName();
            item[3] = data.getStreetName();
            item[4] = data.getCode();
            item[5] = data.getName();
            item[6] = data.getAddress();
            item[7] = String.valueOf(data.getLongitude());
            item[8] = String.valueOf(data.getLatitude());
            dataList.add(item);
        }
        POIUtils.exportExcel(resp, "小区信息", headers, dataList, "小区信息");

    }

    /**
     * 根据参数查询小区分页列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "village:list")
    @Operation(summary = "根据参数查询小区分页列表")
    public Response<Page<VillageDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = villageService.queryTotal(request.getParams());

        List<VillageDto> list = null;
        if (total > 0) {
            list = villageService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<VillageDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<VillageDto>>ok().wrap(page);
    }


    /**
     * 根据id查询小区单条记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "village:info")
    @Operation(summary = "根据id查询小区单条记录")
    public Response<VillageDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (villageService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        VillageDto villageDto = villageService.selectById(id);

        return Response.<VillageDto>ok().wrap(villageDto);
    }

    /**
     * 新增小区单条记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "village:edit")
    @Operation(summary = "新增小区单条记录")
    @Log(express = "新增小区信息")
    public Response<Object> save(@RequestBody @Validated VillageDto villageDto) {


        VillageDto dbValueByCode = villageService.selectByCode(villageDto.getCode());
        if (dbValueByCode != null) {
            return Response.error("小区编码冲突，请更换后重试");
        }
        VillageDto dbValueByName = villageService.selectByName(SessionHolder.getSysUser().getTenantId(), villageDto.getName());
        if (dbValueByName != null) {
            return Response.error("小区名称冲突，请更换后重试");
        }

        //填充基础数据
        fillSaveCommonData(villageDto);

        villageDto.setExtraAttr(JacksonUtils.toJsonString(villageDto.getExtraAttrCls()));

        villageService.save(villageDto);

        return Response.ok();
    }

    /**
     * 编辑小区信息
     */
    @PostMapping("update")
    @RequirePermissions(values = "village:edit")
    @Operation(summary = "编辑小区信息")
    @Log(express = "编辑小区信息")
    public Response<Object> update(@RequestBody @Validated VillageDto villageDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(villageDto.getId()));
        if (villageService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        VillageDto dbValueByCode = villageService.selectByCode(villageDto.getCode());
        if (dbValueByCode != null && !Objects.equals(dbValueByCode.getId(), villageDto.getId())) {
            return Response.error("小区编码冲突，请更换后重试");
        }
        VillageDto dbValueByName = villageService.selectByName(SessionHolder.getSysUser().getTenantId(), villageDto.getName());
        if (dbValueByName != null && !Objects.equals(dbValueByName.getId(), villageDto.getId())) {
            return Response.error("小区名称冲突，请更换后重试");
        }

        //填充基础数据
        fillEditCommonData(villageDto);

        villageDto.setExtraAttr(JacksonUtils.toJsonString(villageDto.getExtraAttrCls()));

        villageService.updateById(villageDto);

        return Response.ok();
    }

    /**
     * 批量删除小区记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "village:delete")
    @Operation(summary = "批量删除小区记录")
    @Log(express = "删除小区信息")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (villageService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
            List<VillageBuildingDto> buildingDtoList = villageBuildingService.selectByVillageId(id);
            if (buildingDtoList != null && buildingDtoList.size() > 0) {
                return Response.error("删除的小区中存在楼栋信息无法删除");
            }
        }


        villageService.deleteBatch(ids);

        return Response.ok();
    }
}
